package com.lagou.consumer;

import com.lagou.service.TpMonitorService;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.lang.reflect.Method;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <h1>服务消费者主类</h1>
 * @author yzh
 */
public class Consumer {

    public static void main(String[] args) {
        //创建线程池
        ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
        //读取消费者配置文件
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"classpath:dubbo-consumer.xml"});
        //获得服务提供者对象
        TpMonitorService tpMonitorService = context.getBean(TpMonitorService.class);
        //获得服务提供者的所有方法
        Method[] methods = TpMonitorService.class.getMethods();
        //根据方法数量创建相同数量的线程并且并行循环执行
        for (int i = 0; i < methods.length; i++) {
            final int index = i;
            cachedThreadPool.execute(() -> {
                while (true) {
                    try {
                        Method method = TpMonitorService.class.getMethod(methods[index].getName());
                        method.invoke(tpMonitorService);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }
}
